<template>
  <div class="container">
    <el-table
      ref="scrollTable"
      v-loading="selfLoading"
      :highlight-current-row="highlight"
      v-bind="setAttrs(tableAttr)"
      :data="tableData"
      @sort-change="sortChange"
      @selection-change="selectionChange"
      @current-change="handleCurrentChange"
    >
      <!-- <el-table v-loading="loading" v-el-height-adaptive-table="{bottomOffset, adaptive}" :data="tableData" :height="adaptive?height:''" style="width: 100%" @selection-change="selectionChange"> -->
      <el-table-column
        v-if="selectVisible"
        type="selection"
        width="45"
        align="center"
        :selectable="selectable"
      />
      <template v-for="column in columns">
        <el-table-column v-if="column.slots" :key="column.prop" v-bind="setAttrs(column)">
          <template slot-scope="scope">
            <Render
              :custom-data="column.slots"
              :class="column.class"
              :row="scope.row"
              :index="scope.$index"
            />
          </template>
        </el-table-column>
        <el-table-column v-else :key="column.prop" v-bind="setAttrs(column)" />
      </template>
    </el-table>
    <!--分页栏-->
    <!-- 分页 -->
    <Pagination
      :total="total"
      :hidden="hidden"
      :page="pageOpt.pageNum"
      :limit="pageOpt.pageSize"
      :page-sizes="pageSizes"
      @pagination="pagination"
    />
  </div>
</template>
<script>
import Render from './render'
// import { scrollTo } from '@/utils/scroll-to'
import Pagination from '@/components/Pagination'
import request from '@/utils/request'
// import { parseTime } from '@/utils'
import tableScroll from '@/mixins/tableScroll'
import { resetParams } from '@/utils/tableParamsConfig'

export default {
  name: 'SrmTable',
  components: {
    Render,
    Pagination
    // ImagePreview
  },
  mixins: [tableScroll],
  props: {
    // 是否可选
    selectable: {
      type: Function,
      default: () => {
        return function() {
          return true
        }
      }
    },
    highlight: {
      type: Boolean,
      default: false
    },
    contentType: {
      type: String,
      default: 'application/json'
    },
    // 外部传入的table数据源 不走组件内接口
    sourceData: {
      type: Array,
      default: () => []
    },
    // 外部传入数据时，传入分页信息
    pageData: {
      type: Object,
      default: () => { }
    },
    // 控制分页组件的显示隐藏
    hidden: {
      type: Boolean,
      default: false
    },
    isLoad: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => []
    },
    // 是否加载中
    loading: {
      type: Boolean,
      default: false
    },
    // 是否可选择行
    selectVisible: {
      type: Boolean,
      default: false
    },
    // 分页查询数据
    pageRequest: {
      type: Object,
      default: () => ({
        pageNum: 1,
        pageSize: 20
      })
    },
    // 每页条数选择器
    pageSizes: {
      type: Array,
      default: () => [10, 20, 50, 100]
    },
    // table组件的属性设置
    tableAttr: {
      type: Object,
      default: () => ({
        border: false
      })
    },
    // 是否开启table自适应高度 默认关闭
    adaptive: {
      type: Boolean,
      default: false
    },
    // table自适应高度距离底部的高度 开启自适应模式时生效
    bottomOffset: {
      type: Number,
      default: 80
    },
    // table高度 默认100% 开启自适应高度时必须设置高度 不设置高度自适应无效
    height: {
      type: String,
      default: '100%'
    },
    // 后端接口api地址 和请求方式  post|/v2/supplier/order/queryOrderList
    url: {
      type: String,
      default: ''
    },
    // 筛选条件
    params: {
      type: Object,
      default: () => ({})
    }
  },
  provide() {
    return {
      vm: this
    }
  },
  data() {
    return {
      downloadLoading: false,
      // 当前选择项的集合
      selections: [],
      // sourceData: [],
      tableData: [],
      total: 10,
      pageOpt: this.pageRequest,
      queryParams: {}, // 列表查询参数，excel导出时使用
      selfLoading: true
    }
  },
  computed: {
    layout() {
      const layout = ['total', 'prev', 'pager', 'next']
      if (this.pageSizes.length) {
        layout.push('sizes')
      }
      return layout.join(', ')
    }
  },
  watch: {
    sourceData(v) {
      // console.log(v, '131sourceData')
      this.tableData = v
      this.selfLoading = false
      if (this.pageData && JSON.stringify(this.pageData)) {
        this.initPage(this.pageData)
      }
    },
    // 筛选条件变化触发接口调用 更新列表数据
    params: {
      handler(newVal, oldVal) {
        this.pageOpt = { pageNum: 1, pageSize: this.pageOpt.pageSize || 10 }
        this.initTable()
      },
      deep: true
    },
    // table结构变化 重新渲染
    columns() {
      this.$nextTick(() => {
        this.$refs.scrollTable.doLayout()
      })
    }
  },
  mounted() {
    // 有外部数据源注入时不走内部接口
    const { sourceData = [], isLoad } = this
    if (sourceData.length) {
      this.tableData = sourceData
      this.selfLoading = false
    } else {
      this.isLoad && this.initTable()
    }
    if (!isLoad) this.selfLoading = false
  },

  methods: {
    // 重置查询参数
    resetParams(params = {}, pageOpt = {}) {
      return resetParams(params, pageOpt)
    },
    async initTable(v) {
      if ((this.sourceData && this.sourceData.length > 0) || !this.url) {
        return
      }
      this.selfLoading = true
      const realParams = this.resetParams(this.params, this.pageOpt)
      const reqOpt = this.url.split('|')
      const [method, url] = reqOpt[1] ? reqOpt : ['post', reqOpt[0]]

      const reqKey = method.toLowerCase() === 'post' ? 'data' : 'params'
      const { hidden, pageOpt } = this
      const pagePamers = hidden ? {} : pageOpt
      // 将重置后的params赋值给queryParams，父组件可以通过获取该参数，获取查询元素
      this.queryParams = { ...pagePamers, ...realParams }
      try {
        const res = await request({
          url,
          method,
          [reqKey]: { ...pagePamers, ...realParams },
          headers: {
            'Content-Type': this.contentType
          }
        })
        let { list, pageInfo, total, obj, totalOrderPrice = 0 } = res
        console.log(res)
        if (!list && res && res.data) {
          ({ list, pageInfo, total, obj } = res.data)
        }
        this.tableData = list
        this.initPage(pageInfo, total)

        setTimeout(() => { this.selfLoading = false }, 500)
        if (obj) {
          this.$emit('putData', obj)
        }

        this.$emit('totalOrder', totalOrderPrice)

        this.$emit('tableData', list)
      } catch (e) {
        this.selfLoading = false
      }
    },
    // 重置分页信息
    initPage(pageInfo, total) {
      this.total = pageInfo ? (pageInfo.totalCount ? pageInfo.totalCount : pageInfo.total) : ~~total
    },
    // 已选项 多选
    selectionChange(selections) {
      this.selections = selections
      this.$emit('selectionChange', { selections })
    },
    handleCurrentChange(val) {
      this.$emit('handleCurrentChange', val)
    },
    // 排序
    sortChange(v) {
      this.$emit('sort-change', v)
    },
    getSummaries(v) {
      // console.log(v, 'vvvvv')
      this.$emit('getSummaries', v)
    },
    setAttrs(params) {
      // eslint-disable-next-line
      const { ...options } = params
      if (!options.align) {
        options.align = 'center'
      }
      return { ...options }
    },
    // 分页
    pagination(ev) {
      const { page, limit } = ev
      this.pageOpt.pageNum = page
      this.pageOpt.pageSize = limit
      this.initTable()
      this.$emit('pagination', ev)
    },
    // 清除排序
    clearSort() {
      this.$refs.scrollTable.clearSort()
    }
  }
}
</script>
<style lang="scss" scoped>
// .container{
//   // padding: 0 15px;
// // }
.srm-table_img {
  cursor: pointer;
}
.toolbar {
  margin-top: 15px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .handle-wrap {
    position: absolute;
    left: 0;
  }
}
.handle-wrap {
  display: flex;
  align-items: center;
  text-align: center;
  margin-bottom: 15px;
}
* + .table-export_btn {
  margin-left: 15px;
}
</style>
